package com.imooc.sell.controller;

import com.imooc.sell.converter.OrderForm2OrderDTOConverter;
import com.imooc.sell.dto.OrderDTO;
import com.imooc.sell.enums.ResultEnum;
import com.imooc.sell.exception.SellException;
import com.imooc.sell.form.OrderForm;
import com.imooc.sell.service.BuyerService;
import com.imooc.sell.service.OrderService;
import com.imooc.sell.utils.ResultVoUtil;
import com.imooc.sell.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/buyer/order")
public class BuyerOrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private BuyerService buyerService;

    @PostMapping("/create")
    public ResultVo<Map<String,String>> create(@Valid OrderForm orderForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO orderDTO= OrderForm2OrderDTOConverter.convert(orderForm);
        OrderDTO result=orderService.create(orderDTO);

        Map<String,String> map=new HashMap<>();
        map.put("orderId",result.getOrderId());

        return ResultVoUtil.success(map);
    }

    @GetMapping("/list")
    public ResultVo<List<OrderDTO>> list(@RequestParam String openid,
                                         @RequestParam(defaultValue = "0") Integer page,
                                         @RequestParam(defaultValue = "10") Integer size){
        if(StringUtils.isEmpty(openid)){
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        PageRequest pageRequest=new PageRequest(page,size);
        Page<OrderDTO> orderDTOPage=orderService.findList(openid,pageRequest);

        return ResultVoUtil.success(orderDTOPage.getContent());
    }

    @GetMapping("/detail")
    public ResultVo<OrderDTO> detail(@RequestParam String openid,
                                     @RequestParam String orderId){
        OrderDTO orderDTO= buyerService.findOrderOne(openid, orderId);
        return ResultVoUtil.success(orderDTO);
    }

    @PostMapping("/cancel")
    public ResultVo cancel(@RequestParam String openid,
                           @RequestParam String orderId){
        buyerService.cancelOrder(openid, orderId);
        return ResultVoUtil.success();
    }
}
